package com.da.javatest.mock;

import com.da.javatest.util.MyUtil;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * @author: chenlida
 * @date: 2018/11/29 09:58
 * @description:
 */
@Component
public class MyUtilProxy implements BeanPostProcessor {

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof MyUtil) {
            return mockMyUtil((MyUtil)bean);
        }
        return bean;
    }

    private Object mockMyUtil(MyUtil bean) {
        ProxyFactory proxyFactory = new ProxyFactory();
        //植入切面
        proxyFactory.addAdvice(new MockMyUtil());
        //设置被代理对象
        proxyFactory.setTarget(bean);
        //使用cglib
        proxyFactory.setOptimize(true);
        //冻结切面
        proxyFactory.setFrozen(true);
        //获取被代理的对象
        Object result = proxyFactory.getProxy();
        //返回被代理的对象
        return result;
    }

    class MockMyUtil implements MethodInterceptor {
        @Override
        public Object invoke(MethodInvocation invocation) throws Throwable {
            if (StringUtils.equals(invocation.getMethod().getName(), "getName")) {
                return "JokerDa.";
            } else {
                return invocation.proceed();
            }
        }

    }
}
